<template>
  <div class="layout">
    <Sidebar />
    <div class="charity-container">
      <a-card class="box-card">
        <template #title>
          <span>慈善项目管理</span>
        </template>

        <!-- 统计信息 -->
        <a-row :gutter="20" class="statistics-row">
          <a-col :span="12">
            <a-card hoverable>
              <div class="statistics-item">
                <div class="title">项目总数</div>
                <div class="value">{{ projectCount }}</div>
              </div>
            </a-card>
          </a-col>
          <a-col :span="12">
            <a-card hoverable>
              <div class="statistics-item">
                <div class="title">申请总数</div>
                <div class="value">{{ applicationCount }}</div>
              </div>
            </a-card>
          </a-col>
        </a-row>

        <!-- 活跃项目列表 -->
        <a-card class="section-card">
          <template #title>
            <span>活跃项目列表</span>
          </template>
          <a-table
              :columns="activeProjectColumns"
              :data-source="activeProjects"
              :loading="isLoadingActiveProjects"
              row-key="projectId"
          >
            <template #bodyCell="{ column, record }">
              <template v-if="column.dataIndex === 'status'">
                <a-tag color="green">{{ record.status }}</a-tag>
              </template>
            </template>
          </a-table>
        </a-card>

        <!-- 项目详情 -->
        <a-form :model="projectForm" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" class="project-form">
          <a-form-item label="项目ID">
            <a-input v-model:value="projectForm.projectId" placeholder="请输入项目ID" />
          </a-form-item>
          <a-form-item :wrapper-col="{ offset: 6 }">
            <a-button type="primary" @click="getProjectDetails">查询项目详情</a-button>
          </a-form-item>
        </a-form>

        <a-card v-if="projectDetails" class="project-details">
          <template #title>
            <span>项目详情</span>
          </template>
          <a-descriptions bordered>
            <a-descriptions-item label="项目名称">{{ projectDetails.projectName }}</a-descriptions-item>
            <a-descriptions-item label="描述">{{ projectDetails.description }}</a-descriptions-item>
            <a-descriptions-item label="受益人地址">{{ projectDetails.beneficiaryAddress }}</a-descriptions-item>
            <a-descriptions-item label="目标金额">{{ projectDetails.targetAmount }}</a-descriptions-item>
            <a-descriptions-item label="当前金额">{{ projectDetails.currentAmount }}</a-descriptions-item>
            <a-descriptions-item label="状态">{{ formatProjectStatus(projectDetails.status) }}</a-descriptions-item>
          </a-descriptions>
        </a-card>

        <!-- 捐赠记录 -->
        <a-card v-if="donationRecords.length > 0" class="donation-records">
          <template #title>
            <span>捐赠记录</span>
          </template>
          <a-table :data-source="donationRecords" :columns="donationColumns" />
        </a-card>

        <!-- 系统信息 -->
        <a-card class="system-info">
          <template #title>
            <span>系统信息</span>
          </template>
          <a-descriptions bordered>
            <a-descriptions-item label="合约地址">{{ contractAddress }}</a-descriptions-item>
            <a-descriptions-item label="慈善组织地址">{{ charityOrg }}</a-descriptions-item>
            <a-descriptions-item label="监管机构地址">{{ regulator }}</a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-card>
    </div>
  </div>
</template>
<script>
import { message } from 'ant-design-vue';
import axios from 'axios';
import Sidebar from '../components/Siderbar.vue';

export default {
  name: 'the-Charity',
  components: {
    Sidebar
  },
  data() {
    return {
      projectCount: 0,
      applicationCount: 0,
      projectForm: {
        projectId: ''
      },
      projectDetails: null,
      donationRecords: [],
      activeProjects: [], // 活跃项目列表
      isLoadingActiveProjects: false, // 活跃项目加载状态
      contractAddress: '',
      charityOrg: '',
      regulator: '',
      donationColumns: [
        {
          title: '捐赠者地址',
          dataIndex: 'donorAddress',
          key: 'donorAddress',
        },
        {
          title: '捐赠金额',
          dataIndex: 'amount',
          key: 'amount',
        },
        {
          title: '捐赠时间',
          dataIndex: 'timestamp',
          key: 'timestamp',
          customRender: ({ text }) => {
            return this.formatTimestamp(text)
          }
        },
      ],
      activeProjectColumns: [
        {
          title: '项目ID',
          dataIndex: 'projectId',
          key: 'projectId',
        },
        {
          title: '项目名称',
          dataIndex: 'projectName',
          key: 'projectName',
        },
        {
          title: '描述',
          dataIndex: 'description',
          key: 'description',
        }
      ]
    };
  },
  created() {
    this.fetchInitialData();
    this.fetchActiveProjects(); // 页面加载时获取活跃项目列表
  },
  methods: {
    formatProjectStatus(status) {
      const statusMap = {
        0: 'Pending',
        1: 'Active',
        2: 'Completed',
        3: 'Rejected',
      };
      return statusMap[status] || '未知状态';
    },

    formatTimestamp(timestamp) {
      if (!timestamp) return '';
      const date = new Date(Number(timestamp) * 1000); // 将秒级时间戳转换为毫秒级
      const month = String(date.getUTCMonth() + 1).padStart(2, '0');
      const day = String(date.getUTCDate()).padStart(2, '0');
      const hours = String(date.getUTCHours()).padStart(2, '0');
      const minutes = String(date.getUTCMinutes()).padStart(2, '0');
      const seconds = String(date.getUTCSeconds()).padStart(2, '0');
      return `${month}-${day} ${hours}:${minutes}:${seconds}`;
    },

    async fetchInitialData() {
      try {
        // 获取项目数量
        const projectCountRes = await axios.get('/api/charity/project/count');
        this.projectCount = projectCountRes.data;

        // 获取申请数量
        const applicationCountRes = await axios.get('/api/charity/application/count');
        this.applicationCount = applicationCountRes.data;

        // 获取合约地址
        const contractAddressRes = await axios.get('/api/charity/contract/address');
        this.contractAddress = contractAddressRes.data;

        // 获取慈善组织地址
        const charityOrgRes = await axios.get('/api/charity/charity-org');
        this.charityOrg = charityOrgRes.data;

        // 获取监管机构地址
        const regulatorRes = await axios.get('/api/charity/regulator');
        this.regulator = regulatorRes.data;
      } catch (error) {
        message.error('获取数据失败：' + error.message);
      }
    },

    async fetchActiveProjects() {
      try {
        this.isLoadingActiveProjects = true;
        const response = await axios.get('/api/charity/getAllActiveProjects');
        if (response.data) {
          this.activeProjects = response.data.map(project => ({
            projectId: project.projectId,
            projectName: project.projectName,
            description: project.description,
            beneficiaryAddress: project.beneficiaryAddress,
            targetAmount: project.targetAmount,
            currentAmount: project.raisedAmount,
            status: this.formatProjectStatus(project.status)
          }));
        }
      } catch (error) {
        message.error('获取活跃项目失败：' + error.message);
      } finally {
        this.isLoadingActiveProjects = false;
      }
    },

    async getProjectDetails() {
      if (!this.projectForm.projectId) {
        message.warning('请输入项目ID');
        return;
      }
      try {
        // 获取项目详情
        const projectDetailsRes = await axios.get(`/api/charity/project/${this.projectForm.projectId}`);
        this.projectDetails = projectDetailsRes.data;

        // 获取捐赠记录
        const donationRecordsRes = await axios.get(`/api/charity/project/${this.projectForm.projectId}/donations`);
        this.donationRecords = donationRecordsRes.data;
      } catch (error) {
        message.error('获取项目详情失败：' + error.message);
      }
    }
  }
};
</script>
<style scoped>
.layout {
  display: flex;
  min-height: 100vh;
}

.charity-container {
  padding: 20px;
  flex: 1;
  margin-left: 256px; /* 修改为与侧边栏宽度相同 */
}

.statistics-row {
  margin-bottom: 20px;
}

.statistics-item {
  text-align: center;
}

.statistics-item .title {
  font-size: 14px;
  color: #666;
  margin-bottom: 10px;
}

.statistics-item .value {
  font-size: 24px;
  color: #1890ff;
  font-weight: bold;
}

.project-form {
  margin-bottom: 20px;
}

.project-details,
.donation-records,
.system-info {
  margin-bottom: 20px;
}

/* 卡片样式优化 */
.box-card {
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}

/* 表格样式优化 */
:deep(.ant-table-thead > tr > th) {
  background-color: #f5f5f5;
}

/* 描述列表样式优化 */
:deep(.ant-descriptions-bordered .ant-descriptions-item-label) {
  background-color: #fafafa;
  font-weight: 500;
}

/* 活跃项目表格样式 */
:deep(.ant-table-tbody > tr > td) {
  text-align: center;
}
</style>